﻿using System;
using System.Web.UI;
using Microsoft.SharePoint;
using RoketSolutions.SP2010.Infrostructure.UI.Controls.Interfaces;
using RoketSolutions.SP2010.LinkedInWebPart.WebParts;

namespace RoketSolutions.SP2010.LinkedInWebPart.CONTROLTEMPLATES.RoketSolutions.SP2010.LinkedInWebPart
{
    public partial class LinkedInToolPartControl : UserControl, IToolPartControl<LinkedInWebPartSettings>
    {
        public Control Control
        {
            get { return this; }
        }

        private LinkedInWebPartSettings _currentSettings;

        private LinkedInWebPartSettings CurrentSettings
        {
            get { return _currentSettings ?? (_currentSettings = ViewState["CurrentSettings"] as LinkedInWebPartSettings); }
            set { ViewState["CurrentSettings"] = _currentSettings = value; }
        }

        private bool IsInitPhase { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (SPContext.Current.Web.CurrentUser.IsSiteAdmin)
            {
                ControlMultiView.SetActiveView(linkedInAppSettngsView);
                if (IsInitPhase)
                {
                    BindData();
                }
            }
        }

        public void Initialize(LinkedInWebPartSettings settings)
        {
            if (CurrentSettings == null)
            {
                CurrentSettings = settings;
                IsInitPhase = true;
            }
        }

        public LinkedInWebPartSettings SaveData()
        {
            if (CurrentSettings != null)
            {
                UpdateConfig(CurrentSettings);
                return CurrentSettings;
            }
            return null;
        }

        private void BindData()
        {
            TextBoxAppKey.Text = CurrentSettings.ApplicationKey;
            TextBoxAppSecret.Text = CurrentSettings.ApplicationSecret;
        }

        private void UpdateConfig(LinkedInWebPartSettings currentSettings)
        {
            currentSettings.ApplicationKey = TextBoxAppKey.Text;
            currentSettings.ApplicationSecret = TextBoxAppSecret.Text;
        }
    }
}
